from ast import Num
from django.core.cache import cache
from app.views.annotate import (
    checkLoginHandling,
)
import json
from app.views.DBUtils import DBUtil
from ..common import  HttpSuccess, upload


@checkLoginHandling
def getMessageList(request):
    token = request.META.get("HTTP_X_TOKEN")
    openid = cache.get(token)
    sql = f"""
    select m.id,m.personone_openid,m.persontwo_openid,u1.nick_name as nick_name1,u2.nick_name as nick_name2,u1.img_url as img_url1,u2.img_url as img_url2 from messageView m 
    left join user u1 on m.personone_openid = u1.openid 
    left join user u2 on m.persontwo_openid = u2.openid 
    where personone_openid = '{openid}' or persontwo_openid = '{openid}' """
    _, result = DBUtil.execute_select(sql)
    for item in result:
        item["me_name"] = (
            item["nick_name1"]
            if openid == item["personone_openid"]
            else item["nick_name2"]
        )
        item["you_name"] = (
            item["nick_name2"]
            if openid == item["personone_openid"]
            else item["nick_name1"]
        )
        item["me_img_url"] = (
            item["img_url1"] if openid == item["personone_openid"] else item["img_url2"]
        )
        item["you_img_url"] = (
            item["img_url2"] if openid == item["personone_openid"] else item["img_url1"]
        )
        sql = f"select * from  messagesinger where parent_viewId = {item['id']} order by create_time desc"
        _,res = DBUtil.execute_select(sql)
        item["singer_first"] = res[0]
    return HttpSuccess(data=result)


@checkLoginHandling
def getMessageDetail(request):
    params = json.loads(request.body)
    id = params.get("id")
    sql = f"""
        select m.id,m.send_openid,m.accept_openid,u1.nick_name as nick_name1,u2.nick_name as nick_name2,u1.img_url as img_url1,u2.img_url as img_url2,m.content,m.create_time 
        from messagesinger m 
        left join user u1 on m.send_openid = u1.openid 
        left join user u2 on m.accept_openid = u2.openid 
        where m.parent_viewId = {id}
        order by m.create_time ASC;"""
    _, result = DBUtil.execute_select(sql)
    list = []
    for index, item in enumerate(result):
        if index == 0:
            list.append(item)
        if index == len(result) - 1:
            break
        current_time = item["create_time"]
        next_time = result[index + 1]["create_time"]
        if next_time.timestamp() - current_time.timestamp() > 2 * 60:
            list.append({"time": result[index + 1]["create_time"]})
        list.append(result[index + 1])
    return HttpSuccess(data=list)
